package com.chenju.invokechainservice.component;

import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

@Component
public class GitComponent {

    @Value(value = "${gitlab.username}")
    private String username;

    @Value(value = "${gitlab.password}")
    private String password;

    public Git cloneRepository(String giturl, String codePath, String commitId) throws GitAPIException{
        File dir = new File(codePath);
        // 清空目录
        if (dir.isDirectory()){
            try {
                FileUtils.cleanDirectory(dir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Git git =Git.cloneRepository()
                .setURI(giturl)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider("chenju","12345678"))
                // .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username,password))
                .setDirectory(dir)
                .setBranch(commitId).call();
        checkoutBranch(git, commitId);
        return git;
    }

    private static Ref checkoutBranch(Git git, String branch){
        try {
            return git.checkout()
                    .setName(branch)
                    .call();
        } catch (GitAPIException e){
            throw new IllegalStateException(e);
        }
    }

    public static void main(String[] args) throws GitAPIException {
        GitComponent git = new GitComponent();
        git.cloneRepository("http://192.168.92.132:9090/easytestgroup/springcloud-easytest.git", "D:\\Project\\testgit\\master", "master");
        git.cloneRepository("http://192.168.92.132:9090/easytestgroup/springcloud-easytest.git", "D:\\Project\\testgit\\feature", "20230801");
    }
}
